<?php

/**
 * Iddy proxy PHP script
 * 
 * @id $Id: iddy.php 55 2009-02-15 16:39:56Z holy.shared.design $
 * @author Noritaka Horio <holy.shared.design@gmail.com>
 * @license Public Domain
 * @version 1.0 $Date: 2009-02-16 01:39:56 +0900 (月, 16 2 2009) $ $Revision: 55 $
 * @see http://iddy.jp/
 * @copyright 2009 Noritaka Horio All rights reserved.
 */

	//Iddy API Key
	define("IDDY_APIKEY", "3a8f2466bd202490a7c1fd4add3d86901bcdfe7a");

	//Iddy Account name
	define("IDDY_ACCOUNT_NAME", "holy");

	//Iddy API Parameters	
	$restParameters = array(
		"type", "sort", "page", "perpage", "searchmode",
		"accountname", "gender", "age", "country",
		"pref", "hometown", "personaltag", "favoritemovie",
		"favoritefood", "favoritemusic", "hobby"
	);

	$userResponseParameters = array(
		"accountname", "profileurl", "imageurl", "birthday",
		"gender", "country", "pref", "hometown",
		"mail", "profile", "personaltag", "favoritemovie", "favoritemusic",
		"favoritefood", "hobby"
	);

	$request = ($_SERVER["REQUEST_METHOD"] == "GET") ? $_GET : $_POST;

	$queryString = "";
	foreach($request as $key => $value) {
		$queryString .= (in_array($key, $restParameters)) ? "&".$key."=".$value : "";
	}

	//Request URL
	$url  = "http://iddy.jp/api/user/";
	$url .= "?apikey=".IDDY_APIKEY;
	$url .= "&accountname=".IDDY_ACCOUNT_NAME;
	$url .= $queryString;


	$response = simplexml_load_string(file_get_contents($url));

	$users			= $response->users;
	$userList		= $response->users->user;
	$responseAttributes 	= $response->attributes();
	$usersAttributes	= $users->attributes();

	$responseString  = "{";
	$responseString .= "\"status\":\"".$responseAttributes->status."\",";
	$responseString .= "\"page\":".$usersAttributes->page.",";
	$responseString .= "\"pages\":".$usersAttributes->pages.",";
	$responseString .= "\"perpage\":".$usersAttributes->perpage.",";
	$responseString .= "\"total\":".$usersAttributes->total.",";
	$responseString .= "\"users\":[";
	foreach ($userList as $user) {
		$userData = array();
		$userResponse .= "{";

		$data = array();
		foreach($userResponseParameters as $propertyName) {
			if (isset($user->$propertyName) && !is_null($user->$propertyName)) {
				$escape = str_replace(
					array("\n", "\r", "\t"),
					array("\\n","\\r", "\\t"),
					$user->$propertyName
				);
				array_push($data, "\"".$propertyName."\":\"".$escape."\"");
			}
		}
		$userResponse .= join($data, ",");
		$userResponse .= "}";
		array_push($userData, $userResponse);
	}
	$responseString .= join($userData, ",");
	$responseString .= "]";
	$responseString .= "}";

	echo $responseString;
?>